<?php

namespace App\Http\Controllers\Admin\Ads;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Ads\Category;

class CategoryController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_ads' => 'active open',
            '_category' => 'active',
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::with('ads')->orderBy('sort_order')->get();
        return view('admin.ads.category.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.ads.category.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:marks|max:255',
            'sort_order' => 'required|integer|max:99',
        ]);

        Category::create($request->all());
        return redirect(route('ads.category.index'))->with('success', '新增分类成功~');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $category = Category::find($id);
        return view('admin.ads.category.edit', compact('category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'sort_order' => 'required|integer|max:99',
        ]);
        $category = Category::find($id);
        $category->update($request->all());
        return redirect(route('ads.category.index'))->with('success', '编辑分类成功~');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Category::destroy($id);
        return back()->with('success', '删除分类成功~');
    }
}
